package com.example.mallapi.interceptor;/*
@author name
@data 2023/5/31-20:10
*/


import com.example.mallapi.common.Constants;
import com.example.mallapi.exception.BusinessException;
import com.example.mallapi.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //检查用户是否携带token 表示他没有登录
        String token = request.getHeader("Authorization");
        if(token == null){
            throw new BusinessException("检测到未登录，请先登录");
        }

        //检测当前登录是否失效:检查redis是否有token的key
        if(!redisUtils.exists(Constants.LOGIN_ADMIN_INFO_TOKEN + token)){
            throw new BusinessException("登录失效，请重新登录");
        }
        return true; // 放行
    }
}
